package com.gxc.datacore.metadata.util;

import java.beans.PropertyVetoException;

import javax.sql.DataSource;

import com.gxc.datacore.db.dialect.Dialect;
import com.gxc.datacore.metadata.domain.Database;
import com.gxc.datacore.metadata.domain.DatabaseType;
import com.gxc.datacore.metadata.service.DatabaseTypeService;
import com.gxc.webcore.util.ContextUtil;
import com.gxc.webcore.util.StringUtil;
import com.mchange.v2.c3p0.ComboPooledDataSource;

public class DataSourceUtil {

	/**
	 * 解析DataSource
	 * 
	 * @param dsDbcp
	 * @return
	 */
	public static DataSource parseToDataSource(Database database) {
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		// driver
		String driverClassName = getJdbcDriver(database);
		if (driverClassName != null) {
			try {
				dataSource.setDriverClass(driverClassName);
			} catch (PropertyVetoException e) {
				e.printStackTrace();
			}
		}
		// jdbc_url
		String jdbc_url = getJdbcUrl(database);
		dataSource.setJdbcUrl(jdbc_url);
		dataSource.setUser(database.getUsername());
		dataSource.setPassword(database.getPassword());
		dataSource.setInitialPoolSize(database.getInitial_pool_size());
		dataSource.setMinPoolSize(database.getMin_pool_size());
		dataSource.setMaxPoolSize(database.getMax_pool_size());
		dataSource.setMaxIdleTime(database.getMax_idle_time());
		dataSource.setIdleConnectionTestPeriod(database
				.getIdle_connection_test_period());
		dataSource.setAcquireIncrement(database.getAcquire_increment());
		dataSource
				.setAcquireRetryAttempts(database.getAcquire_retry_attempts());
		return dataSource;
	}

	/**
	 * 解析JdbcUrl
	 * 
	 * @param dsDbcp
	 * @return
	 */
	public static String getJdbcUrl(Database database) {
		if (StringUtil.isEmpty(database.getJdbc_url())) {
			DatabaseTypeService typeService = (DatabaseTypeService) ContextUtil
					.getBean(DatabaseTypeService.class);
			DatabaseType type = typeService.retrieve(database.getDb_type());
			try {
				Class<?> clazz = Class.forName(type.getDialect_class());
				Dialect dialect = (Dialect) clazz.newInstance();
				return dialect.buildJdbcURL(database.getDb_host(),
						database.getDb_port(), database.getDatabase_name());
			} catch (Exception e) {
				e.printStackTrace();
			}
		} else {
			return database.getJdbc_url().trim();
		}
		return null;
	}

	/**
	 * 解析DriverClass
	 * 
	 * @param dsDbcp
	 * @return
	 */
	public static String getJdbcDriver(Database database) {
		DatabaseTypeService typeService = (DatabaseTypeService) ContextUtil
				.getBean(DatabaseTypeService.class);
		DatabaseType type = typeService.retrieve(database.getDb_type());
		return type.getJdbc_driver();
	}

}
